package com.warthur.jfinal.demo.validator;

import com.jfinal.core.Controller;
import com.jfinal.validate.Validator;
import com.warthur.jfinal.demo.common.ErrorCode;
import com.warthur.jfinal.demo.controller.BaseController;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.Map;


/**
 * @author warthur
 * @date 2019/10/08
 */
@Slf4j
public abstract class BaseValidator<T> extends Validator {

    @Getter
    private T object;

    protected Map<String, String> ret = new LinkedHashMap<>();

    protected void validateRequiredString(String attr, String errorMessage) {
        BaseController baseController = (BaseController) controller;

        try {
            Field field = getObject().getClass().getDeclaredField(attr);
            field.setAccessible(true);
            if (StringUtils.isEmpty((CharSequence) field.get(getObject()))) {
                super.invalid = true;
                ret.put(field.getName(), errorMessage);
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            log.error("失败：", e);
            baseController.renderError(500, ErrorCode.REQUEST_ERROR);
        }
    }

    @Override
    protected void handleError(Controller c) {
        BaseController controller = (BaseController) c;
        controller.renderError(ErrorCode.REQUEST_PARAM_ERROR, ret);
    }
}
